package com.atguigu.netty.groupchart;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class GroupchatServerHandler extends SimpleChannelInboundHandler<String> {

    // 定义channel组，管理所有channel
    // GlobalEventExecutor.INSTANCE全局时间执行器，是一个单例
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * handlerAdded 表示连接建立，第一个执行的方法
     * 将当前channel加入到channelGroup
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 将该客户加入聊天的信息推送给其他在线的客户端
        channelGroup.writeAndFlush(LocalDateTime.now().format(formatter) + "[客户端]" + channel.remoteAddress() + "加入聊天\n");
        channelGroup.add(channel);
    }

    /**
     * handlerRemoved 断开连接 ，将该客户端离开消息推送给其他在线客户端
     * 会自动从channelGroup中删除该channel
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 将该客户加入聊天的信息推送给其他在线的客户端
        channelGroup.writeAndFlush(LocalDateTime.now().format(formatter) +  "[客户端]" + channel.remoteAddress() + "离开聊天\n");
        System.out.println("channelGroup size: " + channelGroup.size());
    }

    /**
     * channelActive 表示channel处于活动状态，可用于用户上线提示
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println( LocalDateTime.now().format(formatter) + "[客户端]" + ctx.channel().remoteAddress() + "上线\n");
    }

    /**
     * channelInactive 表示channel处于不活动状态，可用于用户下线提示
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(LocalDateTime.now().format(formatter) +  "[客户端]" + ctx.channel().remoteAddress() + "下线 \n");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        // 遍历 channelGroup
        channelGroup.forEach(ch -> {
            if (channel != ch) {
                ch.writeAndFlush(LocalDateTime.now().format(formatter) + "[客户端]" + channel.remoteAddress() + "发送了消息：" + msg + "\n");
            }else {
                ch.writeAndFlush(LocalDateTime.now().format(formatter) + "[自己]发送了消息：" + msg + "\n");

            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
